#include <iostream>
#include "../source/http/http_connection.h"
#include "../source/http/http_parser.h"
#include "../source/IOmanager.h"

//测试存活时间
void test_connection_pool()
{
    framework::http::HttpConnectionPool::ptr pool(new framework::http::HttpConnectionPool(
      "www.sylar.top", "", 80, false, 10, 1000 * 10, 5));

    auto r = pool->doGet("/", 300);
    std::cout << r->toString() << std::endl;

    sleep(2);

    auto r2 = pool->doGet("/", 300);
    std::cout << r2->toString() << std::endl;

    sleep(8);

    auto r3 = pool->doGet("/", 300);
    std::cout << r2->toString() << std::endl;
}

//测试访问数量
void test_connection_pool_num()
{
    framework::http::HttpConnectionPool::ptr pool(new framework::http::HttpConnectionPool(
       "www.sylar.top", "", 80, false, 10, 1000 * 10, 5));

    framework::IOManager::GetThis()->addTimer(1000, [pool](){
        auto r = pool->doGet("/", 300);
        std::cout << r->toString() << std::endl;
        std::cout << "===============================================" << std::endl;
    }, true);
}


void run() //测试分块数据
{
    framework::Address::ptr addr = framework::Address::LookupAnyIPAddress("www.sylar.top:80");
    if(!addr)
    {
        std::cout << "get addr error" << std::endl;
    }
    // std::cout << "addr: " << addr->toString() << std::endl;
    framework::Socket::ptr sock = framework::Socket::CreateTCP(addr);
    bool rt = sock->connect(addr);
    if(!rt)
    {
        std::cout << "connect " << *addr << " failed\n";
        return; 
    }
    std::cout << "local ip: " << *sock->getLocalAddress() << std::endl;

    framework::http::HttpConnection::ptr conn(new framework::http::HttpConnection(sock));
    framework::http::HttpRequest::ptr req(new framework::http::HttpRequest);
    req->setPath("/blog/");
    req->setHeader("host", "www.sylar.top");

    std::cout << *req << std::endl;
    

    conn->sendRequest(req);
    auto rsp = conn->recvResponse();
    if(!rsp)
    {
        std::cout << "recv response error" << std::endl;
        return;
    }
    std::cout << "rsp: " << std::endl << *rsp << std::endl;
}

void test_HttpResult()
{
    auto r = framework::http::HttpConnection::DoGet("http://www.sylar.top/blog/", 300);
    std::cout << r->toString() << std::endl;
    std::cout << "===========================================================" << std::endl;
    // if(r->response)
    // {
    //     std::cout << r->response->toString() << std::endl;
    // }

}

int main(void)
{
    framework::IOManager iom(2);
    // iom.schedule(run);
    // iom.schedule(test_HttpResult);

    // iom.schedule(test_connection_pool);
    iom.schedule(test_connection_pool_num);
    return 0;
}